//////////////////////////////////////////////////////////////////
// MattiseOS Kernel
// Date: 2008
// Author: Matthew Iselin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//////////////////////////////////////////////////////////////////

// Includes
#include <mattise.h>
#include <stdint.h>
#include <mem/util.h>
#include <kernio/common.h>

// Functions

// the helper function for sprintf (ie, what the formatter calls)
int sprintf_helper( uint8_t c, void** ptr )
{
    // save the character to the buffer (and then update the buffer pointer)
    uint8_t* dst = (uint8_t*) *ptr;
    *dst++ = c;
    *ptr = (void*) dst;
    return 0;
}

// the sprintf formatter call function
int sprintf_format( char* buff, const char* fmt, va_list args )
{
    // save it all - make sure to append a null byte!
    int rv = 0;
    rv = formatted_out_do( fmt, args, sprintf_helper, (void*) buff );
    buff[rv] = 0;
    return rv;
}

// wrapper for the above
int sprintf( char* buff, const char* fmt, ... )
{
    // setup the argument list
    va_list args;
    va_start( args, fmt );

    // this will hold the number of characters printed
    int rv = 0;

    // print!
    rv = sprintf_format( buff, fmt, args );

    // end the argument list loading
    va_end( args );

    // return the number of characters read
    return rv;
}
